package com.example.mainstream.ui.merchant;

import android.Manifest;
import android.os.Build;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;

import com.amap.api.location.AMapLocation;
import com.bumptech.glide.Glide;
import com.example.shopapp.App;
import com.example.shopapp.R;
import com.example.shopapp.bean.Goods;
import com.example.shopapp.dao.GoodsDao;
import com.example.shopapp.database.GreenDaoManager;
import com.example.shopapp.databinding.ActivityAddGoodBinding;
import com.example.shopapp.utils.ImageEngine;
import com.example.shopapp.utils.ItemChooseUtil;
import com.example.shopapp.utils.LocalUtil;
import com.example.shopapp.utils.Utils;
import com.example.shopapp.widget.I_itemSelectedListener;
import com.huantansheng.easyphotos.EasyPhotos;
import com.huantansheng.easyphotos.callback.SelectCallback;
import com.huantansheng.easyphotos.models.album.entity.Photo;
import com.huantansheng.easyphotos.utils.permission.PermissionUtil;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Arrays;

import cn.project.base.baseui.BaseNormalActivity;

public class AddGoodActivity extends BaseNormalActivity<ActivityAddGoodBinding> {
    String url = "";
    String goodType = "";
    boolean isGet = false;
    GoodsDao goodsDao;
    @Override
    protected int getLayoutId() {
        return R.layout.activity_add_good;
    }

    @Override
    protected void initView() {
        goodsDao = GreenDaoManager.getmInstance().getDaoSession().getGoodsDao();
        final String[] permissions; // 声明一个字符串数组变量permissions

        // 判断当前Android版本是否大于S_V2
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.S_V2){
            permissions = new String[]{ // 如果大于S_V2，则将以下权限添加到permissions数组中
                    Manifest.permission.CAMERA,
                    Manifest.permission.READ_MEDIA_AUDIO,
                    Manifest.permission.READ_MEDIA_VIDEO,
                    Manifest.permission.READ_MEDIA_IMAGES};
        }else {
            permissions =new String[]{ // 如果小于等于S_V2，则将以下权限添加到permissions数组中
                    Manifest.permission.CAMERA,
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE};
        }

        // 检查并请求权限
        if (PermissionUtil.checkAndRequestPermissionsInActivity(AddGoodActivity.this,
                permissions)) {
            preLoadAlbums(); // 如果权限请求成功，则调用preLoadAlbums()方法
        }

        //获取位置数据
        LocalUtil localUtil = new LocalUtil(getApplicationContext());
        localUtil.startLocation();
        localUtil.setOnItemClickListener(new LocalUtil.OnItemClickListener() {
            @Override
            public void onItemClick(double longitude, double latitude, AMapLocation location, String count, String address) {
                if (!isGet){
                    isGet = true;
                    Utils.ADDRESS = location.getProvince()+"-"+location.getDistrict();
                    Utils.DETAIL_ADDRESS = location.getAddress();
                    mBinding.edtAddress.setText(Utils.ADDRESS);
                    mBinding.edtDetailAddress.setText(Utils.DETAIL_ADDRESS);
                }
            }
        });

        mBinding.toolbar.rlBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mBinding.toolbar.tvTitle.setText("添加商品");
        mBinding.tvStype.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ItemChooseUtil.showItemWheel(AddGoodActivity.this, Arrays.asList(Utils.stypeStr), "类别", 0, new I_itemSelectedListener() {
                    @Override
                    public void onItemSelected(int currentPosition) {
                        mBinding.tvStype.setText(Utils.stypeStr[(currentPosition)]);
                        goodType = Utils.stypeStr[(currentPosition)];
                        mBinding.tvDes.setVisibility(View.GONE);
                    }
                });
            }
        });

        mBinding.tvOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String title = mBinding.edtGoodsTitle.getText().toString();
                String price = mBinding.edtPrice.getText().toString();
                String content = mBinding.edtContent.getText().toString();
                String address = mBinding.edtAddress.getText().toString();
                String detail_address = mBinding.edtDetailAddress.getText().toString();
                if (TextUtils.isEmpty(price) || TextUtils.isEmpty(content)
                || TextUtils.isEmpty(address) || TextUtils.isEmpty(detail_address)
                ){
                    showToast("请检查输入信息是否完整");
                    return;
                }
                if (TextUtils.isEmpty(url)){
                    showToast("请添加商品封面");
                    return;
                }
                if (TextUtils.isEmpty(goodType)){
                    showToast("请添加商品类别");
                    return;
                }
                Goods goods = new Goods();
                goods.setIsHelpPoor("0");
                goods.setPrice(price);
                goods.setId(System.currentTimeMillis());

                goods.setDetail_address(detail_address);
                goods.setAddress(address);

                goods.setTitle(title);
                goods.setContent(content);
                goods.setNum(0);
                goods.setUserid(App.getInstance().merchant.getId());
                goods.setUrl(url);
                goods.setTime(Utils.getTime());
                goods.setGoods_type(goodType);

                goodsDao.insert(goods);
                EventBus.getDefault().postSticky("商品");
                showToast("添加成功");
                finish();
            }
        });


    }

    @Override
    protected void initData() {
        mBinding.imgUrl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EasyPhotos
                        .createAlbum(AddGoodActivity.this, true,true, ImageEngine.getInstance())
                        .setCount(1)
                        .setFileProviderAuthority("com.example.shopapp.fileprovider")
                        .start(new SelectCallback() {
                            @Override
                            public void onResult(ArrayList<Photo> photos, boolean isOriginal) {
                                //获取file，进行对应操作
                                if (photos.size()>0){
                                    url =  photos.get(0).path;
                                    Glide.with(AddGoodActivity.this).load(url).into(mBinding.imgUrl);
                                }
                            }
                            @Override
                            public void onCancel() {

                            }
                        });
            }
        });

    }


    /**
     * 预加载相册扫描，可以增加点速度，写不写都行
     * 该方法如果没有授权读取权限的话，是无效的，所以外部加不加权限控制都可以，加的话保证执行，不加也不影响程序正常使用。
     */
    private void preLoadAlbums() {
        EasyPhotos.preLoad(AddGoodActivity.this);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull final String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        PermissionUtil.onPermissionResult(AddGoodActivity.this, permissions, grantResults,
                new PermissionUtil.PermissionCallBack() {
                    @Override
                    public void onSuccess() {
                        preLoadAlbums();
                    }

                    @Override
                    public void onShouldShow() {
                    }

                    @Override
                    public void onFailed() {
                    }
                });
    }
}
